package com.love_weinuo.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.TileOverlay;
import com.amap.api.maps.model.TileOverlayOptions;
import com.amap.api.maps.model.UrlTileProvider;
import com.lzy.okgo.callback.StringCallback;
import com.love_weinuo.R;
import com.love_weinuo.bean.Location;
import com.love_weinuo.databinding.ActivityGaodeMapToBinding;
import com.love_weinuo.util.BHThreadPool;
import com.love_weinuo.util.CenterPointUtil;
import com.love_weinuo.util.GsonUtil;
import com.love_weinuo.util.HTTPAPI;
import com.love_weinuo.util.LogUtil;
import com.love_weinuo.util.PermissionUtil;
import com.love_weinuo.util.SpUtils;
import com.love_weinuo.util.dialog.InputLandNameDialog;
import com.love_weinuo.util.gaodeutil.GaodeUtils;
import com.love_weinuo.util.listener.OnLandNameInputListener;
import com.love_weinuo.util.maputil.MapImageCache;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static com.love_weinuo.bean.Constants.LOGINPRESSION;
import static com.love_weinuo.bean.Constants.REQEEST_CDOE_GPS;

/**
 * Created by Administrator
 * on 2019/2/20.
 */

public class GaodeMap2Activity extends BaseActivity implements View.OnClickListener {

    boolean isShow = true;
    Location location = new Location();
    AMapLocationClient mLocationClient = null;
    AMapLocationClientOption mLocationOption = null;
    MyAMapLocationListener listener = new MyAMapLocationListener();
    MapView mMapView = null;
    AMap aMap;
    ActivityGaodeMapToBinding binding;
    public TextView btn_start, btn_extract, btn_undo, btn_end;
    public TextView textView_map;
    public List<LatLng> listGps = new ArrayList<>();//gps坐标集合 TODO
    public List<LatLng> listBGps = new ArrayList<>();//点击的gps标点集合
    public List<Polyline> listLine = new ArrayList<>();//线段集合
    public List<Marker> listMarker = new ArrayList<>();//线段集合
    public boolean tag = false;
    //图片缓存地址
    private final static String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/amapdemo/Cache/";
    private TileOverlay mtileOverlay;
    String userId = (String) SpUtils.get("module_user_id", "");
    List<LatLng> lists = new ArrayList();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_gaode_map_to);
        binding.setActivity(this);
        mMapView = findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        initPermission();
        setTitleText("地图");
        setRightText("保存");
        btn_start = findViewById(R.id.btn_start);
        btn_extract = findViewById(R.id.btn_extract);
        btn_undo = findViewById(R.id.btn_undo);
        btn_end = findViewById(R.id.btn_end);
        textView_map = findViewById(R.id.textView_map);
        setBack();
    }

    private void initPermission() {
        if (PermissionUtil.loginPermission(this, LOGINPRESSION)) {
            if (!PermissionUtil.isOPen(GaodeMap2Activity.this)) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, REQEEST_CDOE_GPS);
            } else {
                initLocation();
            }
        }
    }

    int a = 0;

    //初始化地图
    private void initLocation() {
        mLocationClient = new AMapLocationClient(this);
        mLocationClient.setLocationListener(listener);
        mLocationOption = new AMapLocationClientOption();

        //设置单次定位
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);

        //设置多次定位，时间为1000毫秒
        //        mLocationOption.setInterval(1000);

        mLocationOption.setNeedAddress(true);
        mLocationOption.setMockEnable(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationClient.startLocation();

        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.myLocationType((MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE));//连续定位
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(getResources().getColor(R.color.A1E0F2));
        myLocationStyle.strokeWidth(1);
        myLocationStyle.radiusFillColor(getResources().getColor(R.color.HALFA1E0F2));

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                //aMap.clear(true);
                //                CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(latLng.latitude, latLng.longitude), 15, 30, 0));
                //                aMap.animateCamera(mCameraUpdate);
                //                aMap.addMarker(myAddMarker(new LatLng(latLng.latitude, latLng.longitude)));
                //拖拽监听
                //                aMap.setOnMarkerDragListener(markerDragListener);
                Log.e("GAODE22", "点击的位置-lat：" + latLng.latitude + "lon:" + latLng.longitude);
                listBGps.add(latLng);
                if (listBGps != null && listBGps.size() > 1) {
                    //画线
                    List<LatLng> lisas = new ArrayList<LatLng>();
                    lisas.add(listBGps.get(listBGps.size() - 2));
                    lisas.add(listBGps.get(listBGps.size() - 1));
                    polyLine(lisas);
                }
                //绘制标记点
                Marker marker = aMap.addMarker(myAddMarker(latLng));
                listMarker.add(marker);
            }
        });
        if (mtileOverlay != null) {
            mtileOverlay.remove();
        }
        useOMCMap();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rightText:
                if (sizeAll == 0) {
                    showInCommonDialog("请测绘您的土地");
                    return;
                }

                if (!isOver) {
                    showInCommonDialog("请确认测绘完成");
                    return;
                }
                InputLandNameDialog dialog = new InputLandNameDialog(this);
                dialog.show();
                dialog.setOnLandNameClickListener(new OnLandNameInputListener() {
                    @Override
                    public void setOnLandNameInputListener(String landName) {
                        String result = "";
                        for (LatLng list : listBGps) {
                            result = result + list.latitude + "," + list.longitude + ";";
                        }
                        LatLng latLng = CenterPointUtil.getCenterPoint(listBGps);
                        HTTPAPI.getInstance().addLand(landName, userId,
                                result.substring(0, result.length() - 1),
                                sizeAll + "",
                                latLng.latitude + "",
                                latLng.longitude + "",
                                distance + "",
                                area + "",
                                new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        showInCommonDialog("土地创建成功");
                                        finish();
                                    }

                                    @Override
                                    public void onError(Call call, Response response, Exception e) {
                                        showInCommonDialog(e.getMessage());
                                    }
                                });
                    }
                });
                break;
            case R.id.btn_start:
                if (listGps.size() == 0) {
                    Toast.makeText(GaodeMap2Activity.this, "没有获取到GPS坐标!请检查权限!", Toast.LENGTH_SHORT).show();
                    return;
                }
                btn_start.setText("记录中");
                btn_start.setClickable(false);
                tag = true;
                listBGps.add(listGps.get(listGps.size() - 1));
                aMap.addMarker(myAddMarker(listBGps.get(0)));
                break;
            case R.id.btn_extract:
                if (!tag) {
                    Toast.makeText(GaodeMap2Activity.this, "请点击开始按钮!", Toast.LENGTH_SHORT).show();
                    return;
                }
                listBGps.add(listGps.get(listGps.size() - 1));
                if (listBGps != null && listBGps.size() > 1) {
                    LogUtil.e("listBGps开始添加坐标");
                    List<LatLng> lisas = new ArrayList<LatLng>();
                    lisas.add(listBGps.get(listBGps.size() - 2));
                    lisas.add(listBGps.get(listBGps.size() - 1));
                    polyLine(lisas);
                } else {
                    LogUtil.e("listBGps个数-->" + listBGps.size());
                }
                break;
            case R.id.btn_undo:
                if (listLine.size() == 0 || listLine == null) {
                    return;
                }
                if (isOver) {
                    isOver = false;
                    listLine.get(listLine.size() - 2).remove();
                    listLine.get(listLine.size() - 1).remove();
                    listLine.remove(listLine.size() - 2);
                    listLine.remove(listLine.size() - 1);
                    listBGps.remove(listBGps.size() - 1);
                    listMarker.get(listMarker.size() - 1).remove();
                    listMarker.remove(listMarker.size() - 1);
                } else {
                    listLine.get(listLine.size() - 1).remove();
                    listLine.remove(listLine.size() - 1);
                    listBGps.remove(listBGps.size() - 1);
                    listMarker.get(listMarker.size() - 1).remove();
                    listMarker.remove(listMarker.size() - 1);
                }
                break;
            case R.id.btn_end:
                if (listBGps == null || listBGps.size() == 1) {
                    return;
                }
                //画线
                List<LatLng> lisas = new ArrayList<>();
                lisas.add(listBGps.get(listBGps.size() - 1));
                lisas.add(listBGps.get(0));
                polyLine(lisas);
                isOver = true;
                lists.addAll(listBGps);
                lists.add(listBGps.get(0));
                for (int i = 0; i < lists.size() - 1; i++) {
                    distance += AMapUtils.calculateLineDistance(lists.get(i),
                            lists.get(i + 1));
                }
                area = AMapUtils.calculateArea(listBGps);
                sizeAll = (int) Math.floor(AMapUtils.calculateArea(listBGps) / 666.67);
                textView_map.setText(sizeAll + "");
                break;
            default:
        }
    }

    //亩数
    int sizeAll = 0;
    //周长
    float distance = 0;
    //面积
    float area = 0;
    //完成是否点击
    boolean isOver = false;

    /**
     * 加载在线瓦片数据
     */
    private void useOMCMap() {
        final String url = "http://www.google.cn/maps/vt?lyrs=y&gl=cn&x=%d&s=&y=%d&z=%d";
        TileOverlayOptions tileOverlayOptions = new TileOverlayOptions().tileProvider(new UrlTileProvider(256, 256) {
            @Override
            public URL getTileUrl(int x, int y, int zoom) {
                try {
                    String mFileDirName;
                    String mFileName;
                    mFileDirName = String.format("L%02d/", zoom + 1);
                    mFileName = String.format("%s", TileXYToQuadKey(x, y, zoom));
                    String LJ = ALBUM_PATH + mFileDirName + mFileName;
                    if (MapImageCache.getInstance().isBitmapExit(mFileDirName + mFileName)) {
                        return new URL("file://" + LJ);
                    } else {
                        String filePath = String.format(url, x, y, zoom);
                        Bitmap mBitmap;
                        mBitmap = getImageBitmap(getImageStream(filePath));
                        try {
                            saveFile(mBitmap, mFileName, mFileDirName);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return new URL(filePath);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
        tileOverlayOptions.diskCacheEnabled(false).diskCacheDir("/storage/emulated/0/amap/OMCcache").diskCacheSize(1024000).memoryCacheEnabled(true).memCacheSize(102400).zIndex(-9999);
        if (mtileOverlay == null) {
            mtileOverlay = aMap.addTileOverlay(tileOverlayOptions);
        } else {
            LogUtil.e("mtileOverlay为空");
        }
    }

    /**
     * 保存文件
     */
    public void saveFile(final Bitmap bm, final String fileName, final String fileDirName) throws IOException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (bm != null) {
                        File dirFile = new File(ALBUM_PATH + fileDirName);
                        if (!dirFile.exists()) {
                            dirFile.mkdir();
                        }
                        File myCaptureFile = new File(ALBUM_PATH + fileDirName + fileName);
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                        bos.flush();
                        bos.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 瓦片数据坐标转换
     */
    private String TileXYToQuadKey(int tileX, int tileY, int levelOfDetail) {
        StringBuilder quadKey = new StringBuilder();
        for (int i = levelOfDetail; i > 0; i--) {
            char digit = '0';
            int mask = 1 << (i - 1);
            if ((tileX & mask) != 0) {
                digit++;
            }
            if ((tileY & mask) != 0) {
                digit++;
                digit++;
            }
            quadKey.append(digit);
        }
        return quadKey.toString();
    }

    public InputStream getImageStream(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return conn.getInputStream();
        }
        return null;
    }

    public Bitmap getImageBitmap(InputStream imputStream) {
        // 将所有InputStream写到byte数组当中
        byte[] targetData = null;
        byte[] bytePart = new byte[4096];
        while (true) {
            try {
                int readLength = imputStream.read(bytePart);
                if (readLength == -1) {
                    break;
                } else {
                    byte[] temp = new byte[readLength + (targetData == null ? 0 : targetData.length)];
                    if (targetData != null) {
                        System.arraycopy(targetData, 0, temp, 0, targetData.length);
                        System.arraycopy(bytePart, 0, temp, targetData.length, readLength);
                    } else {
                        System.arraycopy(bytePart, 0, temp, 0, readLength);
                    }
                    targetData = temp;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 指使Bitmap通过byte数组获取数据
        Bitmap bitmap = BitmapFactory.decodeByteArray(targetData, 0, targetData.length);
        return bitmap;
    }

    public MarkerOptions myAddMarker(LatLng latLng) {
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(new LatLng(latLng.latitude, latLng.longitude));
        markerOption.draggable(true);
        View markerView = LayoutInflater.from(this).inflate(R.layout.view_marker, mMapView, false);
        markerOption.icon(BitmapDescriptorFactory.fromView(markerView));
        //引用drawable中的marker作为地图上的图标
        //        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_activity_gaode_map_location)));
        markerOption.setFlat(false);
        return markerOption;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOGINPRESSION:
                initGPS();
                break;
            case REQEEST_CDOE_GPS:
                initLocation();
                break;
            default:
        }
    }

    public void initGPS() {
        if (!PermissionUtil.isOPen(this)) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, REQEEST_CDOE_GPS);
        } else {
            initLocation();
        }
    }


    class MyAMapLocationListener implements AMapLocationListener {
        @Override
        public void onLocationChanged(final AMapLocation aMapLocation) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    if (isShow) {
                        location.setLatitude(aMapLocation.getLatitude());
                        location.setLongitude(aMapLocation.getLongitude());
                        location.setAddress(aMapLocation.getAddress());
                        location.setCountry(aMapLocation.getCountry());
                        location.setCity(aMapLocation.getCity());
                        location.setDistrict(aMapLocation.getDistrict());
                        location.setStreet(aMapLocation.getStreet());
                        location.setStreetNum(aMapLocation.getStreetNum());
                        location.setCityCode(aMapLocation.getCityCode());
                        location.setAdCode(aMapLocation.getAdCode());
                        location.setPoiName(aMapLocation.getPoiName());
                        location.setAoiName(aMapLocation.getAoiName());
                        location.setErrorCode(aMapLocation.getErrorCode());
                        String result = GsonUtil.BeanToJson(location).toString();
                        LogUtil.e(result);
                        listGps.add(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
                    }
                }
            };
            BHThreadPool.getInstance().executeTask(runnable);
        }
    }

    public void hua() {
        // 定义多边形的5个点点坐标
        LatLng latLng1 = new LatLng(34.761961, 113.768454);
        LatLng latLng2 = new LatLng(34.763935, 113.780856);
        LatLng latLng3 = new LatLng(34.752476, 113.782659);
        LatLng latLng4 = new LatLng(34.751595, 113.768454);

        // 声明 多边形参数对象
        PolygonOptions polygonOptions = new PolygonOptions();
        // 添加 多边形的每个顶点（顺序添加）
        polygonOptions.add(latLng1, latLng2, latLng3, latLng4);
        polygonOptions.strokeWidth(15) // 多边形的边框
                .strokeColor(Color.argb(50, 1, 1, 1)) // 边框颜色
                .fillColor(Color.argb(1, 1, 1, 1));   // 多边形的填充色

        // 添加一个多边形
        Polygon polygon = aMap.addPolygon(polygonOptions);

        List<GaodeUtils.Poi> list = new ArrayList();
        list.add(new GaodeUtils.Poi(34.761961, 113.768454));
        list.add(new GaodeUtils.Poi(34.763935, 113.780856));
        list.add(new GaodeUtils.Poi(34.752476, 113.782659));
        list.add(new GaodeUtils.Poi(34.751595, 113.768454));
        // list.add(new GaodeUtils.Poi(113.768454,34.761961));
        LogUtil.e("TAGAA", "绘制的面积" + GaodeUtils.getArea(list).doubleValue());
        List<LatLng> lists = new ArrayList();
        lists.add(new LatLng(34.761961, 113.768454));
        lists.add(new LatLng(34.763935, 113.780856));
        lists.add(new LatLng(34.752476, 113.782659));
        lists.add(new LatLng(34.751595, 113.768454));
        LogUtil.e("TAGAA", "绘制的面积2=" + AMapUtils.calculateArea(lists));
    }

    //画线
    public void polyLine(List<LatLng> latLngs) {
        Polyline polyline = aMap.addPolyline(new PolylineOptions().
                addAll(latLngs).width(10).color(getResources().getColor(R.color.A1E0F2)).zIndex(999));
        listLine.add(polyline);
        //polyline.remove();
    }

    //计算多边形面积
    public static float calculateArea(List<LatLng> points) {
        byte i3 = 3;
        if (points != null && points.size() >= i3) {
            double var2 = 0.0D;
            double var4 = 111319.49079327357D;
            int size = points.size();

            for (int i = 0; i < size; ++i) {
                LatLng var8 = points.get(i);
                LatLng var9 = points.get((i + 1) % size);
                double var10 = var8.longitude * var4 * Math.cos(var8.latitude * 0.017453292519943295D);
                double var12 = var8.latitude * var4;
                double var14 = var9.longitude * var4 * Math.cos(var9.latitude * 0.017453292519943295D);
                double var16 = var9.latitude * var4;
                var2 += var10 * var16 - var14 * var12;
            }
            return (float) Math.abs(var2 / 2.0D);
        } else {
            return 0.0F;
        }
    }
}
